package com.xaiojimao.gr_common.exception;

import com.xaiojimao.gr_common.CommonEnum.BizCommonEnum;
import com.xaiojimao.gr_common.dto.Result;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandle {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    private Result methodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder errorBuilder = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(x ->
                errorBuilder.append(x.getField()).append(x.getDefaultMessage()).append(","));
        String errorMsg = errorBuilder.substring(0, errorBuilder.length() - 1);
        log.info("methodArgumentNotValid exception! The reason is:{}",e.getMessage(),e);
        return Result.fail(BizCommonEnum.COMMON_ENUM.getCode(), errorMsg);
    }

    @ExceptionHandler(value = CommonException.class)
    @ResponseBody
    public Result commonException(CommonException e) {
        return Result.fail(e.getErrorCode(), e.getErrorMsg());
    }


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result commonException(Exception e) {
        e.printStackTrace();
        return Result.fail(BizCommonEnum.COMMON_ENUM);
    }

    @ExceptionHandler(value = SignatureException.class)
    @ResponseBody
    public Result SignatureException(Exception e) {
        return Result.fail(BizCommonEnum.USER_TOKEN_ILLEGAL_ERROR.getCode(), BizCommonEnum.USER_TOKEN_ILLEGAL_ERROR.getMsg());
    }

}







